package com.example.xiaoxueqixiangmu.Fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.xiaoxueqixiangmu.LoginActivity;
import com.example.xiaoxueqixiangmu.R;
import com.example.xiaoxueqixiangmu.jiemian.MyAccount;
import com.example.xiaoxueqixiangmu.jiemian.MyContact;
import com.example.xiaoxueqixiangmu.jiemian.MyDialog;
import com.example.xiaoxueqixiangmu.jiemian.editPasswordActivity;
import com.example.xiaoxueqixiangmu.utils.Constant;
import com.example.xiaoxueqixiangmu.utils.NetUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MineFragment extends Fragment {
    private static final String TAG = "MineFragment";
    private ListView MyList;
    private Button btnLogout;
    private SimpleAdapter adapter;
    private List<HashMap<String,Object>> dataList;
    private ProgressDialog pDialog=null;
    private ProgressDialog progressDialog;
    private OkHttpClient client=new OkHttpClient();
    private Handler handler;

    private String[] names=new String[]{"我的联系人","我的账户","我的密码"};
    private int[] imgIds=new int[]{R.drawable.administrator_25,R.drawable.administrator_25,R.drawable.lock_25};
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_mine, container, false);
    }

    class LogoutTask extends AsyncTask<String,String,String>{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog= ProgressDialog.show(getActivity(),null,"正在加载中。。。",false,true);
        }

        @Override
        protected String doInBackground(String... params) {
            String result=null;
            //读取已经存好的sessionId
            SharedPreferences preferences=getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
            String value=preferences.getString("cookie","");
            Log.d(TAG,"doInBackground:读取的sessionId:"+value);

            try {
                Request request=new Request.Builder()
                        .addHeader("Cookie",value)
                        .url(Constant.Host+"/otn/Logout")
                        .build();
                Response response=client.newCall(request).execute();
                result=response.body().string();
                Log.d(TAG,"获取的服务器数据："+result);
            }catch (IOException e){
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (pDialog!=null){
                pDialog.dismiss();
            }
            //"1"
            if ("\"1\"".equals(result)){
                Toast.makeText(getActivity(),"退出成功",Toast.LENGTH_SHORT).show();
                Intent intent=new Intent();
                intent.setClass(getActivity(),LoginActivity.class);
                startActivity(intent);
                getActivity().finish();
            }else if ("\"0\"".equals(result)){
                Toast.makeText(getActivity(), "退出登录失败", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(getActivity(), "服务器错误，请重试", Toast.LENGTH_SHORT)
                        .show();
                Intent intent = new Intent();
                intent.setClass(getActivity(), LoginActivity.class);
                startActivity(intent);
                getActivity().finish();
            }
        }
    }
    @Override
    public void onStart() {
        super.onStart();
        btnLogout = getActivity().findViewById(R.id.btnLogout);
        btnLogout.setOnClickListener(new LogOutListener());
        MyList = (ListView) getActivity().findViewById(R.id.MyList);

        dataList = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> showItem;
        for (int i = 0; i < names.length; i++) {
            showItem = new HashMap<String, Object>();
            showItem.put("img", imgIds[i]);
            showItem.put("text", names[i]);
            dataList.add(showItem);
        }
        adapter = new SimpleAdapter(getActivity(), dataList, R.layout.mylist_layout, new String[]{"img", "text"},
                new int[]{R.id.iv_icon, R.id.iv_text});
        MyList.setAdapter(adapter);
        MyList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (position == 0) {
                  Intent  intent1 = new Intent(getActivity(), MyContact.class);
                    startActivity(intent1);
                } else if ( position== 1) {
                  Intent  intent2 = new Intent(getActivity(), MyAccount.class);
                    startActivity(intent2);
                } else if ( position== 2) {
                    final MyDialog userDialog = new MyDialog(getActivity());
                    userDialog.setIcon(R.mipmap.ic_launcher);
                    userDialog.setTitle("请输入原密码");
                    userDialog.show();
                    Button btn_ok = (Button) userDialog.findViewById(R.id.btn_ok_dialog);
                    Button btn_cancel = (Button) userDialog.findViewById(R.id.btn_cancel_dialog);
                    final EditText et_pwd = (EditText) userDialog.findViewById(R.id.pwd_dialog);
                    btn_ok.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            final  String oldPwd=et_pwd.getText().toString().trim();
                            if (!NetUtils.check(getActivity())){
                                Toast.makeText(getActivity(),"网络异常！",Toast.LENGTH_SHORT).show();
                                return;
                            }
                            //弹出对话框
                            progressDialog=ProgressDialog.show(getActivity(),null,"正在加载中...",false,true);
                            new Thread(){
                                @Override
                                public void run() {
                                    super.run();
                                    String result="";
                                    SharedPreferences preferences=getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
                                    String value=preferences.getString("cookie","");
                                    try {
                                        RequestBody requestBody=new FormBody.Builder()
                                                .add("oldPassword",oldPwd)
                                                .add("action","query")
                                                .build();
                                        Request request=new Request.Builder()
                                                .addHeader("Cookie",value)
                                                .url(Constant.Host+"/otn/AccountPassword")
                                                .post(requestBody)
                                                .build();
                                        Response response=client.newCall(request).execute();
                                        result=response.body().string();
                                        if ("\"1\"".equals(result)) {
                                            if (progressDialog != null) {
                                                progressDialog.dismiss();
                                            }
                                            Intent  intent1=new Intent(getActivity(), editPasswordActivity.class);
                                            startActivity(intent1);
                                        }else {
                                            Message message=Message.obtain();
                                            message.what=0x100;
                                            handler.sendMessage(message);
                                        }
                                    }catch (IOException e){
                                        e.printStackTrace();
                                    }
                                }
                            }.start();
                            handler=new Handler(){
                                @Override
                                public void handleMessage(@NonNull Message msg) {
                                    switch (msg.what){
                                        case 0x100:
                                            et_pwd.setError("原密码错误，请重新输入！");
                                            if (progressDialog != null) {
                                                progressDialog.dismiss();
                                            }
                                            break;
                                    }
                                }
                            };
                        }
                    });
                    btn_cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            userDialog.dismiss();
                        }
                    });

                }
            }
        });



    }

    class LogOutListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            //1.检查网络连接是否正常
            if (!NetUtils.check(getActivity())){
                Toast.makeText(getActivity(),"网络异常，请检查",Toast.LENGTH_LONG).show();
                return;//后续代码不执行

            }
            //执行异步任务，退出登录
            new LogoutTask().execute();
        }
    }
    /*class LogoutTask extends  AsyncTask<String,String,String>{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog=ProgressDialog.show(getActivity(),null,"正在加载中.....",false,true);

        }

        @Override
        protected String doInBackground(String... params) {
            String result=null;
            //读取已经存储好的sessionId
            SharedPreferences preferences=getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
            String value=preferences.getString("cookie","");
            Log.d(TAG,"doBackground:读取的sessionID:"+value);

            try {
                OkHttpClient client=new OkHttpClient();
                Request request=new Request.Builder()
                        .addHeader("Cookie",value)
                        .url(Constant.Host+"/otn/Logout")
                        .build();
                Response response=client.newCall(request).execute();
                result=response.body().string();
                Log.d(TAG,"获取的服务器数据："+result);

            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }
        protected void onPostExecute(String result){
            super.onPostExecute(result);
            if (pDialog!=null){
                pDialog.dismiss();
            }
            //如果结果是1，就证明网络没得问题。可以退出
            if ("\"1\"".equals(result)){
                Toast.makeText(getActivity(),"退出成功",Toast.LENGTH_SHORT).show();

                Intent intent=new Intent();
                intent.setClass(getActivity(),LoginActivity.class);
                startActivity(intent);
                getActivity().finish();
            }
            else if("\"0\"".equals(result)){
                Toast.makeText(getActivity(),"退出登录失败！！",Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(getActivity(), "服务器错误，请重试", Toast.LENGTH_SHORT).show();

                Intent intent=new Intent();
                intent.setClass(getActivity(),LoginActivity.class);
                startActivity(intent);
                getActivity().finish();
            }
        }
    }*/

}
